-module(ttim_comet).

-export([start/2, stop/1, call/2]).
-export([init/1]).
start(Name, Data) ->
  Pid = spawn(?MODULE, init, [Data]),
  register(Name, Pid), ok.
  
stop(Name) ->
  Name ! {stop, self()},
  receive {reply, Reply} -> Reply end.
call(Name, Msg) ->
  Name ! {request, self(), Msg},
  receive {reply, Reply} -> Reply end.
reply(To, Msg) ->
  To ! {reply, Msg}.
init(Data) ->
  io:format("init data: ~w ~n ", [Data]),
  loop(Data).

loop(Data)->
    receive
    {keep_alive, NewReq} ->
        io:format("xxx pid is : ~p ~n", [NewReq]), 
	loop([NewReq]);
    {send_msg, Msg} ->
        io:format("Data:~w, Msg: ~p ~n ", [Data, Msg]),
        case Data of 
            P when is_pid(P) ->
                P ! {new_msg, Msg};
            [P2] when is_pid(P2) ->
                P2 ! {new_msg, Msg};
            _ ->
                io:format("no request!~n", [])
        end, 
        loop(Data);
    {router_presence, Stanza} ->
        io:format("comet router presence ~n", []),
        case Data of 
            P when is_pid(P) ->
                P ! {router_presence, Stanza};
            [P2] when is_pid(P2) ->
                P2 ! {router_presence, Stanza};
            _ ->
                io:format("no request!~n", [])
        end, 
        loop(Data);     
    {stop, From}  ->
        reply(From, terminate(Data))
    after 20000 ->
        ok
    end.

terminate(State)    ->  {stop, ok}.
